package com.yanqu.road.server.cmd.activity.dunhuangshiku;

import com.yanqu.road.entity.activity.dunhuangshiku.DunHuangShiKuEventConfig;
import com.yanqu.road.pb.dunhuangshiku.DunHuangShiKuProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.manger.activity.dunhuangshiku.DunHuangShiKuMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;

/**
 * @Description
 * @Author cwq
 * @Data 2021/4/19 18:05
 */
@Cmd(code = GameProtocol.S_DUN_HUANG_SHI_KU_OPEN_BOX, desc = "敦煌石窟打开宝箱")
public class DunHuangShikuOpenBoxCmd extends AbstractCommand {

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        DunHuangShiKuProto.DunHuangShiKuOpenBoxReqMsg req = DunHuangShiKuProto.DunHuangShiKuOpenBoxReqMsg.parseFrom(packet.getBytes());
        int activityId = req.getActivityId();
        ret = DunHuangShiKuMgr.canEnterActivityEndShowTime(player,activityId);
        if(ret != 0){
            return;
        }
        if(req.getNum() <= 0){
            ret = GameErrorCode.E_BAG_USE_GOODS_COUNT_LESS_ONE;
            return;
        }
        // 宝箱对应的事件
        DunHuangShiKuEventConfig eventConfig = DunHuangShiKuMgr.boxEventMap.get(req.getBoxId());
        if(eventConfig == null){
            ret = GameErrorCode.E_DUN_HUANG_SHI_KU_EVENT_NOT_EVENT;
            return;
        }
        Property property = PropertyHelper.parseStringToProperty(eventConfig.getParam());
        property.rideProperty(req.getNum());
        if(!player.getModule(CurrencyModule.class).currencyIsEnough(property)){
            ret = GameErrorCode.E_BAG_ITEM_NO_EXIST;
            return;
        }
        // 预扣除
        player.getModule(PreReduceModule.class).preReduce(property);
        player.sendUnionActivityGroupPacket(CrossProtocol.C2_DUN_HUANG_SHI_KU_OPEN_BOX, req.toBuilder(), req.getActivityId());
    }

    @Override
    public void sendData(GamePlayer player) {
        if (ret != 0) {
            DunHuangShiKuProto.DunHuangShiKuGetUserDataRespMsg.Builder builder = DunHuangShiKuProto.DunHuangShiKuGetUserDataRespMsg.newBuilder();
            builder.setRet(ret);
            player.sendPacket(ClientProtocol.U_DUN_HUANG_SHI_KU_OPEN_BOX, builder);
        }
    }
}
